package com.example.xianzhi.controller.API;

import cn.hutool.json.JSONUtil;
import com.example.xianzhi.entity.TbAdSmall;
import com.example.xianzhi.entity.TbGoods;
import com.example.xianzhi.entity.TbType;
import com.example.xianzhi.service.AdSmallService;
import com.example.xianzhi.service.GoodsService;
import com.example.xianzhi.service.TypeService;
import com.example.xianzhi.service.impl.AdSmallServiceImpl;
import com.example.xianzhi.service.impl.GoodsServiceImpl;
import com.example.xianzhi.service.impl.TypeServiceImpl;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.lanqiao.mvc.entity.YockMvcAnnotation;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@YockMvcAnnotation.Controller("/apl_Goods")
public class Apl_GoodsController {

    //商品的业务层
    private GoodsService goods_sql = new GoodsServiceImpl();
    //分类的业务层
    private TypeService type = new TypeServiceImpl();
    //子图的业务层
    private AdSmallService goods_pic = new AdSmallServiceImpl();


    /**
     * 添加商品
     * @param request
     * @param response
     * @throws Exception
     */
    @YockMvcAnnotation.RequestMapping("/addgoods.do")	//配置二级路径
    @YockMvcAnnotation.ResponseVoid
    public void addgoods(
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception{

        response.setHeader("Access-Control-Allow-Origin", "*");

        String goods_name = request.getParameter("goods_name");
        System.out.println("goods_name is " +goods_name);

        String goods_price = request.getParameter("goods_price");
        System.out.println("goods_price is " +goods_price);

        String goods_now_price = request.getParameter("goods_now_price");
        System.out.println("goods_now_price is " +goods_now_price);

        String describe = request.getParameter("describe");
        System.out.println("describe is " +describe);

        String goods_type_name = request.getParameter("goods_type_name");
        System.out.println("goods_type_name is " +goods_type_name);

        String uploader = request.getParameter("uploader");
        System.out.println("uploader is" +uploader);

        String uploader1 = request.getParameter("uploader1");
        System.out.println("uploader1 is" +uploader1);

        String uploader2 = request.getParameter("uploader2");
        System.out.println("uploader2 is" +uploader2);

        String uploader3 = request.getParameter("uploader3");
        System.out.println("uploader3 is" +uploader3);

        //把分类名称转成分类id
        int type_id=0;
        List<TbType> goods_type_name1 = type.selectType_id(goods_type_name);
        for (TbType tbType : goods_type_name1) {
            type_id=tbType.getType_id();
        }
        System.out.println(type_id);



        TbGoods goods = new TbGoods();

        goods.setGoods_name(goods_name);
        goods.setGoods_picture(uploader);

        //原价
        goods.setGoods_price(Integer.parseInt(goods_price));

        //现价
        goods.setGoods_old_price(Integer.parseInt(goods_now_price));


        goods.setGoods_describe(describe);
        goods.setRelease_id(5);
        goods.setType_id(type_id);

        //获取当前时间
        Date time = new Date();
        System.out.println(time);
        //获得SimpleDateFormat类，我们转换为yyyy-MM-dd的时间格式
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        //把Date转成String
        String format = sf.format(time);
        //在返回转成Date给数据库
        Date date = sf.parse(format);
        System.out.println("date:" + date);
        goods.setRelease_time(date);
        goods.setGoods_state("1");
        //添加商品
        goods_sql.insertGoods(goods);

        //查询该商品id
        List<TbGoods> tbGoods1 = goods_sql.selectGoodsId(goods_name, type_id);
        int goods_id=0;
        for (TbGoods tbGoods : tbGoods1) {
            goods_id=tbGoods.getGoods_id();
        }

        //添加商品的子图2
        goods_pic.insertGoodsPic(uploader1,goods_id);
        //添加商品的子图3
        goods_pic.insertGoodsPic(uploader2,goods_id);
        //添加商品的子图4
        goods_pic.insertGoodsPic(uploader3,goods_id);

    }


    /**
     * 查询商品信息
     * @param request
     * @param response
     * @return
     */
    @YockMvcAnnotation.RequestMapping("/selectgoods.do")
    @YockMvcAnnotation.ResponseBody
    public String selectgoods(
            HttpServletRequest request,
            HttpServletResponse response
    ) {
        //告诉前端返回来的是一个json数据
        response.setContentType("application/json;charset=utf-8");
        // 保存商品信息的集合
        Map<String, Object> map = new HashMap<>();
        //查询商品
        TbGoods tbGoods = goods_sql.selectIdGoods(2);

        map.put("code",200);
        map.put("data",tbGoods);

        String jsonStr = JSONUtil.toJsonStr(map);


        return jsonStr;
    }


    /**
     * 查询商品子图
     * @param request
     * @param response
     * @return
     */
    @YockMvcAnnotation.RequestMapping("/selectgoodspic.do")
    @YockMvcAnnotation.ResponseBody
    public String selectgoodspic(
            HttpServletRequest request,
            HttpServletResponse response
    ) {
        //告诉前端返回来的是一个json数据
        response.setContentType("application/json;charset=utf-8");
        // 保存商品子图的集合
        Map<String, Object> map = new HashMap<>();
        //查询商品子图
        List<TbAdSmall> tbAdSmalls = goods_sql.selectGoodsPic(2);


        map.put("code",200);
        map.put("data",tbAdSmalls);

        String jsonStr = JSONUtil.toJsonStr(map);


        return jsonStr;
    }

    /**
     * 查询发布人的发布了或付款了的订单数据
     * @param request
     * @param response
     * @return
     */
    @YockMvcAnnotation.RequestMapping("/selectReleaseorder.do")
    @YockMvcAnnotation.ResponseBody
    public String selectReleaseorder(
            HttpServletRequest request,
            HttpServletResponse response,
            @YockMvcAnnotation.RequestParam(name = "release_id") String release_id
    ) {
        //允许的请求的域是*，代表所有
        response.setHeader("Access-Control-Allow-Origin","*");
        int release_id1 = 0;
        System.out.println(release_id);
        if(!release_id.equals("") && release_id !=null){
            release_id1=Integer.parseInt(release_id);
        }
        //告诉前端返回来的是一个json数据
        response.setContentType("application/json;charset=utf-8");
        // 保存商品订单的集合
        Map<String, Object> map = new HashMap<>();
        //查询订单数据
        List<TbGoods> tbGoods = goods_sql.selectReleaseOrder(release_id1);


        map.put("code",200);
        map.put("data",tbGoods);

        String jsonStr = JSONUtil.toJsonStr(map);


        return jsonStr;
    }


    /**
     * 查询发布人的订单数据
     * @param request
     * @param response
     * @return
     */
    @YockMvcAnnotation.RequestMapping("/selectgoodsorder.do")
    @YockMvcAnnotation.ResponseBody
    public String selectgoodsorder(
            HttpServletRequest request,
            HttpServletResponse response,
            @YockMvcAnnotation.RequestParam(name = "release_id") int release_id,
            @YockMvcAnnotation.RequestParam(name = "goods_state") String goods_state
    ) {
        //允许的请求的域是*，代表所有
        response.setHeader("Access-Control-Allow-Origin","*");
        System.out.println(release_id);
        System.out.println(goods_state);
        //告诉前端返回来的是一个json数据
        response.setContentType("application/json;charset=utf-8");
        // 保存商品订单的集合
        Map<String, Object> map = new HashMap<>();
        //查询订单数据
        List<TbGoods> tbGoods = goods_sql.selectOrder("1", 1);



        map.put("code",200);
        map.put("data",tbGoods);

        String jsonStr = JSONUtil.toJsonStr(map);


        return jsonStr;
    }

    /**
     * 查询商品详细信息
     * @param request
     * @param response
     * @param goods_id  商品id
     * @return
     */
    @YockMvcAnnotation.RequestMapping("/selectGoodsByGoodsId.do")
    @YockMvcAnnotation.ResponseBody
    public String selectGoodsByGoodsId(
            HttpServletRequest request,
            HttpServletResponse response,
            @YockMvcAnnotation.RequestParam(name = "goods_id") String  goods_id
    ) {
        //允许的请求的域是*，代表所有
        response.setHeader("Access-Control-Allow-Origin","*");
        int goods_id1 =0;
        if(!goods_id.equals("")){
            goods_id1=Integer.parseInt(goods_id);
        }
        System.out.println(goods_id1);
        //告诉前端返回来的是一个json数据
        response.setContentType("application/json;charset=utf-8");
        // 保存商品订单的集合
        Map<String, Object> map = new HashMap<>();
        //查询订单数据
        List<TbGoods> tbGoods = goods_sql.selectGoodsByGoodsId(goods_id1);

        map.put("code",200);
        map.put("data",tbGoods);

        String jsonStr = JSONUtil.toJsonStr(map);


        return jsonStr;
    }

    /**
     * 修改商品订单信息
     * @param request
     * @param response
     * @param buyer_id 购买人id
     * @param goods_add_id 地址id
     * @throws Exception
     */
    @YockMvcAnnotation.RequestMapping("/updateGoodsid.do")	//配置二级路径
    @YockMvcAnnotation.ResponseVoid
    public void updateGoodsid(
            HttpServletRequest request,
            HttpServletResponse response,
            @YockMvcAnnotation.RequestParam(name = "buyer_id") int  buyer_id, //购买人id
            @YockMvcAnnotation.RequestParam(name = "goods_add_id") int  goods_add_id,         // 地址id
            @YockMvcAnnotation.RequestParam(name = "goods_id") int  goods_id         // 商品id
    ) throws Exception{

        //获取当前时间
        Date time = new Date();
        System.out.println(time);
        //获得SimpleDateFormat类，我们转换为yyyy-MM-dd的时间格式
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        //把Date转成String
        String format = sf.format(time);
        //在返回转成Date给数据库
        Date date = sf.parse(format);

        //允许的请求的域是*，代表所有
        response.setHeader("Access-Control-Allow-Origin","*");
        goods_sql.updateGoodsid(buyer_id,date,buyer_id,goods_id);
    }

    /**
     * 通过商品分类id查询商品信息
     *
     * @param request
     * @param response
     * @return
     */
    @YockMvcAnnotation.RequestMapping("/selectTypeGoods.do")
    @YockMvcAnnotation.ResponseBody
    public String selectTypeGoods(
            HttpServletRequest request,
            HttpServletResponse response,
            @YockMvcAnnotation.RequestParam(name = "type_id") int type_id
    ) {
        response.setHeader("Access-Control-Allow-Origin", "*");

        System.out.println("type_id is " + type_id);


        //告诉前端返回来的是一个json数据
        response.setContentType("application/json;charset=utf-8");
        // 保存商品订单的集合
        Map<String, Object> map = new HashMap<>();

        //通过分类id查询商品信息
        List<TbGoods> tbGoods2 = goods_sql.selectTypeGoods(type_id);

        map.put("code", 200);
        map.put("data", tbGoods2);

        String jsonStr = JSONUtil.toJsonStr(map);
        System.out.println(jsonStr);


        return jsonStr;
    }



    /**
     * 图片上传
     *
     * @param request
     * @param response
     * @return
     */
    @YockMvcAnnotation.RequestMapping("/uploadPic.do")
    @YockMvcAnnotation.ResponseBody
    public String uploadPic(
            HttpServletRequest request,
            HttpServletResponse response
    ) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        //告诉前端返回来的是一个json数据
        response.setContentType("application/json;charset=utf-8");
        // 保存图片名称的集合
        Map<String, String> map = new HashMap<>();


        // 获取上传文件对象
        ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
        System.out.println("upload is  " +upload);

        try {
            // 解析请求的内容提取文件数据
            List<FileItem> items = upload.parseRequest(request);
            System.out.println("items is " +items);
            // 迭代表单数据
            for (FileItem item : items) {


                // 循环图片
                if ("pic".equals(item.getFieldName())) {
                    //设置上传图片路径（访问路径）
                    String uploadPath = request.getServletContext().getRealPath("upload");
                    //获取图片上传名称（保证图片的唯一性）
                    String fileName = System.currentTimeMillis() + item.getName();
                    // 把图片加载到路径中（保证图片的唯一性）
                    uploadPath += File.separator + fileName;
                    // 保存文件到硬盘
                    item.write(new File(uploadPath));
                    // 保存图片名称
                    map.put("pic", fileName);
                }




            }

        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //返回图片名称集
        String jsonStr = JSONUtil.toJsonStr(map);
        System.out.println(jsonStr);
        return jsonStr;
    }





    /**......................
     * 查询用户收藏的商品数据(xcc)
     * @param request
     * @param response
     * @return
     */
    @YockMvcAnnotation.RequestMapping("/selegoodsrela.do")
    @YockMvcAnnotation.ResponseBody
    public String selegoodsrela(
            HttpServletRequest request,
            HttpServletResponse response,
            @YockMvcAnnotation.RequestParam(name = "user_id") int user_id
    ) {
        //允许的请求的域是*，代表所有
        response.setHeader("Access-Control-Allow-Origin","*");

        //告诉前端返回来的是一个json数据
        response.setContentType("application/json;charset=utf-8");
        // 保存用户信息的集合
        Map<String, Object> map = new HashMap<>();
        //查询用户收藏的信息
        List<TbGoods> tbGoodsrela = goods_sql.selegooodsrela(user_id);


        map.put("code",200);
        map.put("data",tbGoodsrela);

        String jsonStr = JSONUtil.toJsonStr(map);


        return jsonStr;
    }





    /**
     * 查询用户游览的商品数据(xcc)
     * @param request
     * @param response
     * @return
     */
    @YockMvcAnnotation.RequestMapping("/selectgooshistorypic.do")
    @YockMvcAnnotation.ResponseBody
    public String selectgooshistorypic(
            HttpServletRequest request,
            HttpServletResponse response,
            @YockMvcAnnotation.RequestParam(name = "user_id") int user_id
    ) {
        //允许的请求的域是*，代表所有
        response.setHeader("Access-Control-Allow-Origin","*");

        //告诉前端返回来的是一个json数据
        response.setContentType("application/json;charset=utf-8");
        // 保存用户信息的集合
        Map<String, Object> map = new HashMap<>();
        //查询用户历史游览信息
        List<TbGoods> tbGoods = goods_sql.selegooodsrhist(user_id);


        map.put("code",200);
        map.put("data",tbGoods);

        String jsonStr = JSONUtil.toJsonStr(map);


        return jsonStr;
    }


    /**
     * 查询所有商品（用于我的页面）
     * @param request
     * @param response
     * @return
     */
    @YockMvcAnnotation.RequestMapping("/selectgoodswdsd.do")
    @YockMvcAnnotation.ResponseBody
    public String selectgoodswdsd(
            HttpServletRequest request,
            HttpServletResponse response
    ) {
        //允许的请求的域是*，代表所有
        response.setHeader("Access-Control-Allow-Origin","*");

        //告诉前端返回来的是一个json数据
        response.setContentType("application/json;charset=utf-8");
        // 保存用户信息的集合
        Map<String, Object> map = new HashMap<>();


        //查询商品信息
        List<TbGoods> tbGoods = goods_sql.selectusergoods();
        map.put("code",200);
        map.put("data",tbGoods);

        String jsonStr = JSONUtil.toJsonStr(map);


        return jsonStr;
    }



}
